package fudan.se.lab2.service;

import fudan.se.lab2.controller.request.ApproveRequest;
import fudan.se.lab2.domain.Meeting;
import fudan.se.lab2.exception.MeetingWrongStatusException;
import fudan.se.lab2.repository.MeetingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminService {
    private final MeetingRepository meetingRepository;

    @Autowired
    public AdminService(MeetingRepository meetingRepository) {
        this.meetingRepository = meetingRepository;
    }

    public Meeting approve(ApproveRequest request) {
        Meeting meeting = meetingRepository.findMeetingByFullName(request.getMeetingFullName());
        if (meeting.getStatus() == 0) {
            meeting.setStatus(1);
            meeting.setChair(request.getChair());
            List<String> pcMembers = new ArrayList<>();
            pcMembers.add(request.getChair());
            meeting.setPcMembers(pcMembers);
            meetingRepository.save(meeting);
            return meeting;
        } else {
            throw new MeetingWrongStatusException(request.getMeetingFullName());
        }
    }

    public Meeting reject(ApproveRequest request) {
        Meeting meeting = meetingRepository.findMeetingByFullName(request.getMeetingFullName());
        if (meeting.getStatus() == 0) {
            meeting.setStatus(-1);
            meeting.setChair(request.getChair());
            meetingRepository.save(meeting);
            return meeting;
        } else {
            throw new MeetingWrongStatusException(request.getMeetingFullName());
        }
    }

    public List<Meeting> meetingToBeApproved() {
        Iterable<Meeting> it = meetingRepository.findAll();
        List<Meeting> meetingToBeApproved = new ArrayList<>();
        for (Meeting meeting : it) {
            if (meeting.getStatus() == 0)
                meetingToBeApproved.add(meeting);
        }
        return meetingToBeApproved;
    }

    public List<Meeting> meetingAlreadyApproved() {
        Iterable<Meeting> it = meetingRepository.findAll();
        List<Meeting> meetingAlreadyApproved = new ArrayList<>();
        int meetingStatus;
        for (Meeting meeting : it) {
            meetingStatus = meeting.getStatus();
            if (meetingStatus == 1 || meetingStatus == 2 || meetingStatus == 3 || meetingStatus == 4 || meetingStatus == 5)
                meetingAlreadyApproved.add(meeting);
        }
        return meetingAlreadyApproved;
    }
}
